package com.feiyisys.utils;

import com.feiyisys.config.TencentCosConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Component
public class TencentCosUtil {

    @Resource
    private TencentCosConfig cosConfig;

    /**
     * 初始化COS客户端
     * @return COSClient实例
     */
    private COSClient initCOSClient() {
        // 1.初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
        
        // 2.设置bucket的区域
        Region region = new Region(cosConfig.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        
        // 3.使用HTTPS协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        
        // 4.生成cos客户端
        return new COSClient(cred, clientConfig);
    }

    /**
     * 上传文件到腾讯云COS
     * @param file 文件对象
     * @return 返回文件访问路径
     */
    public String uploadFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }
        
        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String year = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy"));
        String month = LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM"));
        String day = LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd"));
        
        // 文件在COS中的Key，即对象键，使用年月日目录进行分类
        String key = String.format("%s/%s/%s/%s%s", year, month, day, uuid, suffix);
        
        COSClient cosClient = null;
        try {
            // 初始化COS客户端
            cosClient = initCOSClient();
            
            // 获取文件流
            InputStream inputStream = file.getInputStream();
            
            // 创建元数据
            ObjectMetadata metadata = new ObjectMetadata();
            // 设置Content-Type
            metadata.setContentType(file.getContentType());
            metadata.setContentLength(file.getSize());
            
            // 创建请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    cosConfig.getBucketName(), key, inputStream, metadata);
            
            // 上传文件
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            
            // 记录ETag
            log.info("文件上传成功 - Key: {}, ETag: {}", key, putObjectResult.getETag());
            
            // 返回文件路径（不带baseUrl，方便后续灵活处理）
            return key;
            
        } catch (CosServiceException e) {
            log.error("腾讯云COS服务异常 - ErrorCode: {}, ErrorMessage: {}", 
                    e.getErrorCode(), e.getErrorMessage());
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        } catch (CosClientException e) {
            log.error("腾讯云COS客户端异常: {}", e.getMessage());
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        } catch (IOException e) {
            log.error("文件流处理异常: {}", e.getMessage());
            throw new RuntimeException("文件处理失败: " + e.getMessage());
        } finally {
            // 关闭客户端
            if (cosClient != null) {
                cosClient.shutdown();
            }
        }
    }
    
    /**
     * 获取完整的文件访问URL
     * @param key 文件对象键
     * @return 完整的文件访问URL
     */
    public String getFileUrl(String key) {
        if (key == null || key.isEmpty()) {
            return "";
        }
        
        // 如果已经是完整URL，则直接返回
        if (key.startsWith("http://") || key.startsWith("https://")) {
            return key;
        }
        
        // 拼接baseUrl和对象键
        String baseUrl = cosConfig.getBaseUrl();
        if (baseUrl.endsWith("/")) {
            return baseUrl + key;
        } else {
            return baseUrl + "/" + key;
        }
    }
} 